package easyexcel;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import easyexcel.entity.EntityBean;
import easyexcel.entity.OldMan;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class EntityBeanLoadTest {
    private String filename;
    public EntityBeanLoadTest(String arg) {
        this.filename = arg;
    }
    public static void main(String[] args) {
        EntityBeanLoadTest entityBeanLoadTest = new EntityBeanLoadTest("D:\\git\\commons-examples\\alibaba\\src\\main\\java\\easyexcel\\实体和属性.xlsx");
        entityBeanLoadTest.readFile();
    }
    private void readFile() {
        try {
            EntityBeanLoadTest.MyListenerImpl listener1 = new EntityBeanLoadTest.MyListenerImpl();
            EasyExcelFactory.readBySax(new FileInputStream(filename),
                    new Sheet(1,1,EntityBean.class),
                    listener1);


            List<EntityBean> entityBeanList = listener1.getThreadLocal().get();
            for (int i = 0; i < entityBeanList.size(); i++) {
                System.out.println(entityBeanList.get(i));
            }
            List<String> collect = entityBeanList.stream().collect(Collectors.groupingBy(oldMan -> oldMan.getEntNm()))
                    .entrySet().stream().filter(x -> x.getValue().size() > 1).map(x -> x.getKey()).collect(Collectors.toList());

            collect.forEach(x ->System.out.print(x));

        }catch (Exception e){
            e.printStackTrace();
        }


    }

    private class MyListenerImpl  extends AnalysisEventListener {

        private ThreadLocal<List<EntityBean>> threadLocal = ThreadLocal.withInitial(() -> {
            return new ArrayList<EntityBean>();
        });
        List<EntityBean> data = new ArrayList<>();
        @Override
        public void invoke(Object o
                , AnalysisContext analysisContext) {
            EntityBean entityBean = (EntityBean)o;
            if(entityBean.validate()){
                threadLocal.get().add((EntityBean)o);
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            System.out.println("输出完成"+Thread.currentThread().getId());
        }

        public ThreadLocal<List<EntityBean>> getThreadLocal() {
            return threadLocal;
        }
    }
}
